package tree;

import com.sun.source.tree.Tree;

import java.util.*;

/**
 * @Author: Darven
 * @CreateTime: 2025-05-09  08:54
 * @Description: TODO
 */
public class P102 {
    public static void main(String[] args) {
        P102Demo p102Demo = new P102Demo();

    }
}

class P102Demo{
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> levelOrder(TreeNode root) {

        List<List<Integer>> ans=new ArrayList<>();
        if(root==null){
            return ans;
        }
        Queue<TreeNode> q=new LinkedList<>();
        q.offer(root);
        while(!q.isEmpty()){
            int size = q.size();
            List<Integer> list=new ArrayList<>();
            for(int i=0;i<size;i++){
                TreeNode poll = q.poll();
                if(poll!=null){
                    list.add(poll.val);
                    if(poll.left!=null){
                        q.offer(poll.left);
                    }
                    if(poll.right!=null){
                        q.offer(poll.right);
                    }
                }
            }
            ans.add(list);
        }
        return ans;
    }

    public TreeNode sortedArrayToBST(int[] nums) {
        return dfs(nums, 0, nums.length);
    }

    public TreeNode dfs(int[] nums,int left,int right){
        if(left>right){
            return null;
        }
        int mid=(left+right)>>2+1;
        TreeNode root = new TreeNode(nums[mid]);
        root.left=dfs(nums,left,mid-1);
        root.right=dfs(nums,mid+1,right);
        return root;
    }
}
